class Ajax {
  constructor(options) {
    this.$options = options
    this.xhr = new XMLHttpRequest()
    this.open()
  }

  setHeader() {
    let { type, headers } = this.$options
    type = type.toUpperCase()
    if (type === 'POST' && !headers['Content-type'])
      this.xhr.setRequestHeader(
        'Content-type',
        'application/x-www-form-urlencoded;charset=utf-8'
      )
    this.xhr.withCredentials = true
    Object.entries(headers).forEach(([key, value]) => {
      this.xhr.setRequestHeader(key, value)
    })
  }
  request(params) {
    let { request } = this.$options.interceptors
    this.$options = request(this.$options)
    let { url, baseUrl, type } = this.$options
    let requestUrl = baseUrl
    //处理url
    if (url.startsWith('/')) {
      requestUrl += url
    } else {
      requestUrl = `${requestUrl}/${url}`
    }

    type = type.toUpperCase()

    //没有参数，直接发请求
    if (
      !params ||
      Object.prototype.toString.call(params).indexOf('Object') === -1
    ) {
      this.xhr.open(type, requestUrl)
      this.setHeader()

      this.xhr.send()
    } else {
      let formData
      let queryString = ''

      if (type === 'GET') {
        Object.entries(params).forEach(([key, value]) => {
          queryString += `${key}=${value}&`
        })
        queryString = queryString.slice(0, -1)
      } else if (type === 'POST') {
        // formData = new FormData()
        // Object.entries(params).forEach(([key, value]) => {
        //   formData.append(key, value)
        // })
        formData = JSON.stringify(params)
      }

      this.xhr.open(
        type,
        `${requestUrl}${type === 'GET' ? '?' : ''}${queryString}`
      )
      this.setHeader()
      this.xhr.send(formData)
    }
    return this.done()
  }
  done() {
    let { response } = this.$options.interceptors
    let { xhr } = this
    return new Promise((resolve, reject) => {
      xhr.onreadystatechange = function() {
        let { readyState, status, responseText } = xhr
        if (readyState === 4 && status === 200) {
          if (status === 200) {
            try {
              let parse = JSON.parse(responseText)
              let configsRes = response(parse)

              if (configsRes) {
                resolve(configsRes)
              } else {
                reject(parse)
              }
            } catch (e) {
              reject('请求错误')
            }
          } else {
            reject('请求错误')
          }
        }
      }
    })
  }

  open() {}
}

const http = {
  config: {
    // 接口的根路径
    baseUrl: window.globalConfig.apiUrl, //本地代理
    // 设置请求的 header
    headers: {
      'Content-type': 'application/json;charset=utf-8',
      'User-Token': localStorage.getItem('__token__')
    },
    // 自定义请求拦截器（模拟axios）
    interceptors: {
      // 请求拦截
      request(configs) {
        return configs
      },
      // 响应拦截
      response(res) {
        let { data, code, meta } = res
        if (Number(code) === -666) {
          location.href = window.globalConfig.loginUrl
        }
        if (code !== 0) {
          return res
        }
        if (meta === null) {
          return data
        } else {
          return res
        }
      }
    }
  },
  get(url, params) {
    return new Ajax({ type: 'GET', url, ...this.config }).request(params)
  },
  post(url, params) {
    return new Ajax({ type: 'POST', url, ...this.config }).request(params)
  }
}
